package service

import (
	"apitestAfterGo/common"
	"apitestAfterGo/dao"
	"apitestAfterGo/domain"
	"apitestAfterGo/dto"
	"gorm.io/gorm"
	"net/http"
	"strconv"
)

type taskRecordService struct {
	SubmitTask            func(dto domain.TaskRecord) domain.TaskRecord
	FindAllRecordsByPage  func(dto dto.TaskRecordPageInputDto) ([]domain.TaskRecord, int)
	DeleteRecordById      func(id int) bool
	FindRecordsBySystemId func(dto dto.TaskRecordPageInputDto) ([]domain.TaskRecord, int)
}

var TaskRecordServiceImpl taskRecordService

func init() {
	TaskRecordServiceImpl = taskRecordService{
		SubmitTask: func(taskRecord domain.TaskRecord) domain.TaskRecord {
			err := dao.GormDb.Transaction(func(tx *gorm.DB) error {
				// 在事务中执行一些 db 操作（从这里开始，您应该使用 'tx' 而不是 'db'）
				if err := tx.Create(&taskRecord).Error; err != nil {
					// 返回任何错误都会回滚事务
					return err
				}
				// 返回 nil 提交事务
				return nil
			})
			// 调用任务接收器的任务接受接口
			http.Get(common.RabbitMqUrl + "/" + taskRecord.Type + "/" + strconv.Itoa(int(taskRecord.ID)))
			if err != nil {
				panic(err)
			}
			return taskRecord
		},
		FindAllRecordsByPage: func(dto dto.TaskRecordPageInputDto) ([]domain.TaskRecord, int) {
			var taskRecords []domain.TaskRecord
			dto.Current = (dto.Current - 1) * dto.PageSize
			dao.GormDb.Debug().Where("task_name like ? and description like ?", "%"+dto.TaskName+"%", "%"+dto.Description+"%").Limit(dto.PageSize).Offset(dto.Current).Find(&taskRecords)
			var count int64
			dao.GormDb.Debug().Model(&domain.TaskRecord{}).Select("count(1)").Where("task_name like ? and description like ? ", "%"+dto.TaskName+"%", "%"+dto.Description+"%").Count(&count)
			return taskRecords, int(count)
		},
		DeleteRecordById: func(id int) bool {
			dao.GormDb.Debug().Where("id = ?", id).Delete(&domain.TaskRecord{})
			return true
		},
		FindRecordsBySystemId: func(dto dto.TaskRecordPageInputDto) ([]domain.TaskRecord, int) {
			var taskRecords []domain.TaskRecord
			dto.Current = (dto.Current - 1) * dto.PageSize
			dao.GormDb.Debug().Where("task_name like ? and description like ? and system_id =? and type like ?", "%"+dto.TaskName+"%", "%"+dto.Description+"%", dto.SystemId, "%"+dto.Type+"%").Limit(dto.PageSize).Offset(dto.Current).Find(&taskRecords)
			var count int64
			dao.GormDb.Debug().Model(&domain.TaskRecord{}).Select("count(1)").Where("task_name like ? and description like ? and system_id =?", "%"+dto.TaskName+"%", "%"+dto.Description+"%", dto.SystemId).Count(&count)
			return taskRecords, int(count)
		},
	}
}
